﻿/**
 * describe:Reply message packet class
 * date:2022-09-06
 * author:lenny
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Jt808DataParser.Utils
{
    public class ReplayUtil
    {
        /// <summary>
        /// 0x8001 Reply content
        /// </summary>
        /// <param name="terminalNumArr"></param>
        /// <param name="msgFlowId"></param>
        /// <returns></returns>
        public static string reply8001Message(byte[] terminalNumArr, int msgFlowId,int msgId)
        {
            List<byte> byteList = new List<byte>();
            byteList.AddRange(CommonUtil.HexStringToBytes("8001"));
            byteList.AddRange(CommonUtil.HexStringToBytes("0005"));
            byteList.AddRange(terminalNumArr);
            byteList.AddRange(CommonUtil.ShortToBytes(CommonUtil.RandomNumber(0, 65534)));
            byteList.AddRange(CommonUtil.ShortToBytes((short)msgFlowId));
            byteList.AddRange(CommonUtil.ShortToBytes((short)msgId));
            byteList.Add(0x00);
            byteList.Add(CommonUtil.xor(byteList));
            byte[] bytes = CommonUtil.escape(byteList);
            List<byte> replyList = new List<byte>();
            replyList.Add(0x7E);
            replyList.AddRange(bytes);
            replyList.Add(0x7E);
            return CommonUtil.ByteToHexStr(replyList.ToArray());
        }

        /// <summary>
        /// 0x8100 Reply content
        /// </summary>
        /// <param name="terminalNumArr"></param>
        /// <param name="msgFlowId"></param>
        /// <returns></returns>
        public static string reply8100Message(byte[] terminalNumArr, int msgFlowId)
        {
            //Message body
            List<byte> bodyList = new List<byte>();
            bodyList.AddRange(CommonUtil.ShortToBytes((short)msgFlowId));
            bodyList.Add(0x00);
            bodyList.AddRange(terminalNumArr);
            int bodyLen = bodyList.Count();
            //Message body with calculated check code
            List<byte> xorBodyList = new List<byte>();
            xorBodyList.AddRange(CommonUtil.HexStringToBytes("8100"));
            xorBodyList.AddRange(CommonUtil.ShortToBytes((short)bodyLen));
            xorBodyList.AddRange(terminalNumArr);
            xorBodyList.AddRange(CommonUtil.ShortToBytes(CommonUtil.RandomNumber(0, 65534)));
            xorBodyList.AddRange(bodyList);
            xorBodyList.Add(CommonUtil.xor(xorBodyList));
            //Escape
            byte[] escapeBodyArr = CommonUtil.escape(xorBodyList);
            //Get reply message
            List<byte> replyList = new List<byte>();
            replyList.Add(0x7E);
            replyList.AddRange(escapeBodyArr);
            replyList.Add(0x7E);
            return CommonUtil.ByteToHexStr(replyList.ToArray());
        }
    }
}
